package net.togogo;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class helloServlet implements Servlet {

    public helloServlet() {
        System.out.println("1--->：执行构造方法");
    }

    //初始化
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("2--->：执行初始化方法");

        /**
         * - 可以获取servlet程序的别名 servlet-name
         * - 获取初始化参数 init-param
         * - 获取ServletContext对象
         */
        System.out.println("获取servlet程序的别名--->" + servletConfig.getServletName());
        System.out.println("获取初始化参数:username-->" + servletConfig.getInitParameter("username"));
        System.out.println("获取初始化参数:password-->" + servletConfig.getInitParameter("password"));
        System.out.println("获取ServletContext对象-->" + servletConfig.getServletContext());
    }

    //配置
    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        //专门用来处理请求与相应
        System.out.println("3--->执行service方法 helloServlet.service被调用");
        //获取提交的类型 需要将ServletRequest转换成HttpServletRequest 因为它有getMethod()
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String method = httpServletRequest.getMethod();
        System.out.println("获取到的提交方式是：" + method);
        //判断提交方式 作出不同的应答
        if ("POST".equals(method)){
            doPost();
        }else if ("GET".equals(method)){
            doGet();
        }

    }

    public void doPost(){
        System.out.println("执行POST方法");
    }

    public void doGet(){
        System.out.println("执行GET方法");
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    //销毁
    @Override
    public void destroy() {
        System.out.println("4--->：执行销毁方法");
    }
}
